package com.rm.community.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rm.community.common.Result;
import com.rm.community.entity.CommunityLikeToPost;
import com.rm.community.service.ICommunityLikeToPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/communityLike")
public class CommunityLikeToPostController {

    @Autowired
    private ICommunityLikeToPostService likeService;

    // 新增点赞记录（需检查唯一性）
    @PostMapping
    public Result addLike(@RequestBody CommunityLikeToPost like) {
        // 检查是否已存在相同用户和题目的点赞记录
        QueryWrapper<CommunityLikeToPost> query = new QueryWrapper<>();
        query.eq("owner_id", like.getOwnerId())
                .eq("question_id", like.getQuestionId());
        if (likeService.getOne(query) != null) {
            return Result.error("不可重复点赞");
        }

        boolean saved = likeService.save(like);
        return saved ? Result.success("点赞成功") : Result.error("点赞失败");
    }

    // 取消点赞（根据ID删除）
    @DeleteMapping("/{id}")
    public Result cancelLike(@PathVariable Long id) {
        boolean removed = likeService.removeById(id);
        return removed ? Result.success("取消点赞成功") : Result.error("取消点赞失败");
    }

    // 根据用户ID查询点赞记录
    @GetMapping("/byOwner/{ownerId}")
    public Result getByOwner(@PathVariable Long ownerId) {
        QueryWrapper<CommunityLikeToPost> query = new QueryWrapper<>();
        query.eq("owner_id", ownerId);
        return Result.success(likeService.list(query));
    }

    // 根据题目ID查询点赞数量
    @GetMapping("/countByQuestion/{questionId}")
    public Result countByQuestion(@PathVariable Long questionId) {
        QueryWrapper<CommunityLikeToPost> query = new QueryWrapper<>();
        query.eq("question_id", questionId);
        int count = (int) likeService.count(query);
        return Result.success(count);
    }

    // 分页查询所有点赞记录
    @GetMapping("/page")
    public Result page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<CommunityLikeToPost> page = new Page<>(pageNum, pageSize);
        likeService.page(page);
        return Result.success(page);
    }
}